package com.dkd.day20250615;

import com.dkd.day20250614.ListNode;

import java.util.*;

public class SolutionhasCycle {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        System.out.println(hasCycle(head));
    }

    //自己的解发，慢
    public static boolean hasCycle(ListNode head) {
        //f
        boolean flag = false;
        //p判断是否有环，依次将节点的next压入set，当出现重复时，返回true
        Set<ListNode> set = new HashSet<>();
        while (head != null) {
            if (set.contains(head)) {
                flag = true;
                return flag;
            }
            set.add(head);
            head = head.next;
        }
        return flag;
    }

    //快慢指针解法
    public static boolean hasCycle2(ListNode head) {
        if(head == null){
            return false;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                return true;
            }
        }
        return false;
    }
}
